package com.zm.zmgz.utils;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: cjw
 * @Date: 2020/04/07/10:30
 * @Description:sql相关工具类(只适用单表sql)
 * * sql模板:
 *       insert into userzm (id, username, password, identificationNumber, kind, status ) values (null, "asdklfhjasd", "123", "440982199709086337", null, 0 )
 *       update userzm set username = "asdklfhjasd", password = "123", identificationNumber = "440982199709086337", kind = null, status = 1 where id = 10
 *       delete from userzm where id = 10
 *       select id, identificationNumber, path from authorityzm WHERE ( identificationNumber = ? )
 */
public class SqlCjwUtils {

    /***
    * @Description: 传入sql,获取sql类型(增删改查)
    * @Param:
    * @return:
    * @Author: cjw
    * @Date: 2020-04-07 10:31:05
    */
    public static String getSqlType(String sql) {
        String temp = sql;
        if(Objects.isNull(sql) && sql.trim().equals("")) {
            System.err.println("传入sql为空!");
            return null;
        }
        String[][] strings = {{"insert","^insert"},
                {"delete","^delete"},
                {"select","^select"},
                {"update","^update"}};

        // 匹配
        for (String[] string : strings) {
            sql = temp;
            String[] split = sql.split(string[1]);
            if(!Objects.isNull(split) && split.length>1){
                System.out.println(temp+"类型:"+string[0]);
                return string[0];
            }
        }
        System.err.println(temp+"类型提取失败!");
        return null;
    }
    
    /***
    * @Description: 传入sql和sql类型,从sql中提取表名
    * @Param: 
    * @return: 
    * @Author: cjw
    * @Date: 2020-04-07 11:11:38
    */
    public static String getTableName(String sql,String sqlType){
        String temp = sql;
        Map<String,String> map = new HashMap<>();
        map.put("insert","insert into ");
        map.put("delete","delete from ");
        map.put("update","update ");
        map.put("select",".*from ");
        String regular = map.get(sqlType);
        String[] split = sql.split(regular);
        if(!Objects.isNull(split) && split.length>1){
            String[] split1 = split[1].split(" ");
            System.out.println(temp+"表名:"+split1[0]);
            return split1[0];
        } else {
            System.err.println(temp+"获取表名失败!");
            return null;
        }
    }


}
